package com.jiangchuang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiangchuang.domain.entity.Activity;
import com.jiangchuang.mapper.ActivityMapper;
import com.jiangchuang.service.IActivityService;
import com.jiangchuang.service.ICommonService;
import com.jiangchuang.utils.OssUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 活动服务实现类
 */
@Service
public class ActivityServiceImpl implements IActivityService {
    
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    ICommonService commonService;
    
    @Override
    public Activity getLatestActiveActivity() {
        // 创建查询条件
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        // 条件1：活动状态为开启(0)
        queryWrapper.eq("status", 0);
        // 条件2：活动开始时间不晚于当前时间
        queryWrapper.le("begin_time", LocalDate.now());
        // 条件3：活动结束时间不早于当前时间
        queryWrapper.ge("end_time", LocalDate.now());
        // 按id降序排列，获取最新的活动
        queryWrapper.orderByDesc("id");
        // 查询符合条件的活动列表
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        
        // 如果有符合条件的活动，返回第一个（最新的）
        if (activities != null && !activities.isEmpty()) {
            return activities.get(0);
        }
        // 如果没有符合条件的活动，返回空
        return null;
    }

    @Override
    public List<Activity> getAllActivities() {
        // 创建查询条件
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        // 按id降序排列，获取最新的活动在前
        queryWrapper.orderByDesc("id");
        // 查询所有活动
        return activityMapper.selectList(queryWrapper);
    }

    @Override
    public boolean updateActivity(Activity activity) {
        if (activity == null || activity.getId() == null) {
            return false;
        }
        // 使用MyBatis-Plus的updateById方法更新活动信息
        return activityMapper.updateById(activity) > 0;
    }

    @Override
    public String uploadActivityImg(Integer aId, MultipartFile img) {
        Activity activity = activityMapper.selectById(aId);

        // 1. 上传图片
        String url = commonService.uploadImg("activity/", img);

        // 2. 判断是否活动已有图片 若已有图片则删除
        if(!Objects.equals(activity.getImg(), "")){
            OssUtils.deleteFile(activity.getImg());
        }

        // 3. 更新数据库
        activity.setImg(url);
        activityMapper.updateById(activity);

        return url;
    }
}